#include <iostream>
#include <limits>
#include <algorithm>

using namespace  std;

class Solution {
public:
    int nextGreaterElement(int n) {
        string tmpStr = to_string(n);
        if (tmpStr.length() <= 1) {
            return -1;
        }

        return GetNextGreaterElement(tmpStr, n);
    }

    int GetNextGreaterElement(string& numStr, const int n)
    {
        for (int idx = numStr.length() - 2; idx >= 0; --idx) {
            bool flag = false;
            string tmpNumStr(numStr);
            string numSubstr{};
            char minGreaterChar = '9';

            for (int loop = idx + 1; loop < tmpNumStr.length(); ++loop) {
                if (tmpNumStr[loop] > tmpNumStr[idx]) {
                    flag = true;
                    minGreaterChar = min(minGreaterChar, tmpNumStr[loop]);
                }
                numSubstr.push_back(tmpNumStr[loop]);
            }

            if (!flag) {
                continue;
            }

            auto pos = numSubstr.find(minGreaterChar);
            if (pos == string::npos) {
                cout << "numSubstr.find error " << minGreaterChar << endl;
                continue;
            }
            numSubstr[pos] = tmpNumStr[idx];
            tmpNumStr[idx] = minGreaterChar;

            sort(numSubstr.begin(), numSubstr.end());
            tmpNumStr.replace(tmpNumStr.begin() + idx + 1, tmpNumStr.end(), numSubstr);

            long long int tmp = stoll(tmpNumStr);
            if (tmp > numeric_limits<int>::max()) {
                continue;
            }

            if (tmp > n) {
                return static_cast<int>(tmp);
            }
        }

        return -1;
    }
};

int main() {
    std::cout << "Hello, World!" << std::endl;
    int n = 1324;
    Solution solu;
    cout << solu.nextGreaterElement(n) << endl;

    return 0;
}
